
import React, { useEffect, useState, useRef } from 'react'
import { message, Select, Modal as MyModal } from 'antd';

import NotesAPI from "./api";
import Modal from "./components/Modal/Index"
import xmlbuilder from 'xmlbuilder';
import FileSaver from 'file-saver';
const initData = {
  title: "",
  body: "",
}
interface ListType {
  id?: number;
  title: string;
  body: string,
  updated?: string
}
const View: React.FC<any> = props => {


  const [noteList, setNoteList] = useState<Array<ListType>>([]);
  const [visible, setVisible] = useState<boolean>(false);
  const [status, setStatus] = useState<string>('add');
  const [previewData, setPreviewData] = useState<ListType>(initData)
  const [selectedIndex, setSelectedIndex] = useState<number>(0)
  const [confirmVisible, setConfirmVisible] = useState<boolean>(false)
  const [exportconfirmVisible, setExportconfirmVisible] = useState<boolean>(false)
  const [exportType,setExportType] = useState<string>('1')
  const inputRef = useRef<any>();

  useEffect(() => {
    _refreshNotes()
  }, [])

  // note操作
  const _setNotes = (notes: Array<ListType>) => {
    setNoteList(notes)
  }
  const _refreshNotes = () => {
    const notes = NotesAPI.getAllNotes();
    _setNotes(notes);
    if (notes.length > 0) {
      setPreviewData(notes[0])
      setSelectedIndex(0)
    } else {
      setPreviewData(initData)
    }
  }
  const addNote = (newNote: ListType) => {
    NotesAPI.saveNote(newNote);
    _refreshNotes()
  }
  const editNote = (newNote: ListType) => {
    const { id, title, body } = newNote
    NotesAPI.saveNote({
      id,
      title,
      body,
    });
    _refreshNotes()
  }

 
  // 按钮操作
  const clickItem = (list: ListType, index: number) => {
    setPreviewData(list)
    setSelectedIndex(index)
  }
  const addClick = () => {
    setStatus('add')
    setVisible(true)
  }
  const editClick = () => {
    console.log("previewData:", previewData)
    if (!previewData.id) {
      message.warning('没有可以编辑的note')
      return
    }
    setStatus('edit')
    setVisible(true)
  }
  const deleteClick = () => {
    console.log("previewData:", previewData)
    if (!previewData.id) {
      message.warning('没有可以删除的note')
      return
    }
    setConfirmVisible(true)


  }
  const importClick = () => {
    inputRef.current.click()
  }

  const exportClick = () => {
   setExportconfirmVisible(true)
  }

//  文件导入导出
  const saveAsCsv = (fileName: string) => {
   
    const arr = noteList.map(note => [note.title, note.body, note.updated])
    const tableRows = [
      ['title', 'body', 'updated'],
      ...arr
    ]
    let CsvString = tableRows.map(data => data.join(',')).join('\r\n');
    CsvString = 'data:application/vnd.ms-excel;charset=utf-8,\uFEFF' + encodeURIComponent(CsvString);
    const link = document.createElement('a');
    link.href = CsvString;
    link.download = `${fileName}.csv`;
    link.click();
    link.remove();
  }
  const saveAsXml = (fileName: string) => {
    const root = xmlbuilder.create('List');
    noteList.forEach(note => {
      const item = root.ele('note');
      item.ele('title', note.title)
      item.ele('body', note.body)
      item.ele('updated', note.updated)
    })
    const xml = root.end({ pretty: true })
    const blob = new Blob([xml], { type: 'text/xml;charset=utf-8' });
    FileSaver.saveAs(blob, `${fileName}.xml`);
  }
  const readCsv = (e: any) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();

      reader.onload = function (e) {
        var lines = e.target.result.split('\n');
        lines.forEach(function (line, rowIndex) {
          if (rowIndex == 0) return
          console.log(rowIndex + ': ' + line);
          const arr = line.split(',')
          NotesAPI.saveNote({ title: arr[0], body: arr[1] });
        });
        _refreshNotes()
      };

      reader.onerror = function (e) {
        console.error("读取文件时发生错误:", e.target.error);
      };

      reader.readAsText(file);
    }
  }
  const readXml = (e: any) => {
    const file = e.target.files[0];
    if (file) {
      const reader = new FileReader();

      reader.onload = function (e) {
        const xmlData = e.target.result
        var parser = new DOMParser();
        var xml = parser.parseFromString(xmlData, "text/xml");
        if (xml.getElementsByTagName("parsererror").length > 0) {
          throw new Error("Parsing error");
        }

        var note = xml.getElementsByTagName("note");
        for (var i = 0; i < note.length; i++) {
          var title = note[i].getElementsByTagName("title")[0].childNodes[0].nodeValue;
          var body = note[i].getElementsByTagName("body")[0].childNodes[0].nodeValue;
          console.log(title, body);
          NotesAPI.saveNote({ title, body });
        }
        _refreshNotes()
      };


      reader.onerror = function (e) {
        console.error("读取文件时发生错误:", e.target.error);
      };

      reader.readAsText(file);
    }
  }

  const importData = (e: any) => {
    const type = e.target.files[0].type
    if (type.includes('csv')) {
      readCsv(e)
    } else {
      readXml(e)
    }
  }

  // 日期格式
  const DateFormat = (tzDateString: string) => {
    if (!tzDateString) return
    const date = new Date(tzDateString);
    const localDate = new Date(date.getTime() + date.getTimezoneOffset() * 60000);
    const localDateString = localDate.toLocaleDateString();
    return localDateString
  }


  
  const onOk = (data: ListType, status: string) => {
    if (status == 'add') {
      addNote(data)
    } else if (status == 'edit') {
      editNote(data)
    }
  }

  const closeConfirmModal = () => {
    setConfirmVisible(false)
  }
  const onConfirmOk = () => {
    NotesAPI.deleteNote(previewData.id);
    _refreshNotes();
    setConfirmVisible(false)

  }
  const handleChange = (value: string) => {
    console.log(`selected ${value}`);
    setExportType(value)
  };
  const onExportConfirmOk =()=>{
    exportType=='1'?saveAsCsv(new Date().getTime() + ''):saveAsXml(new Date().getTime())
    setExportconfirmVisible(false)
  }
  const oncloseExportConfirmModal =()=>{
    setExportconfirmVisible(false)

  }
  return (
    <>
      <div className="notes__container">
        <div className='notes_header'>
          <button className="notes_btn notes__add" type="button" onClick={addClick}>添加</button>
          <button className="notes_btn notes__edit" type="button" onClick={editClick}>编辑 </button>
          <button className="notes_btn notes__delete" type="button" onClick={deleteClick}>删除 </button>
          <button className="notes_btn import__edit" type="button" onClick={importClick}>导入</button>
          <button className="notes_btn export__edit" type="button" onClick={exportClick}>导出</button>
          <input type="file" accept=".csv,.xml" onChange={importData} style={{ display: 'none' }} ref={inputRef} />
        </div>
        <div className='notes__content'>
          <div className="notes__sidebar">

            <div className="notes__list">
              {
                noteList.map((list, index) => {
                  return <div className={`notes__list-item ${selectedIndex == index ? 'selected' : ''}`} key={list.id} onClick={() => clickItem(list, index)}>
                    <div className="notes__small-title">{list?.title}</div>
                  </div>
                })
              }
            </div>
          </div>
          <div className="notes__preview">
            <h2>{previewData.title}</h2>
            <div className="content">{previewData.body}</div>
            <div className="time"> {DateFormat(previewData.updated)}</div>
          </div>
        </div>
      </div>
      <Modal visible={visible} setVisible={setVisible} onOk={onOk} status={status} editData={status == 'edit' ? previewData : null} />
      <MyModal open={confirmVisible} onOk={onConfirmOk}
        onCancel={closeConfirmModal}
        afterClose={closeConfirmModal}>确认删除？</MyModal>

      <MyModal    open={exportconfirmVisible} onOk={onExportConfirmOk}
        onCancel={oncloseExportConfirmModal}
        afterClose={oncloseExportConfirmModal}>
      <Select
       defaultValue="1"
    
       style={{ width: 120 }}
       onChange={handleChange}
       options={[
         { value: '1', label: 'CSV文件' },
         { value: '2', label: 'XML文件' },
        
       ]}>
      
      </Select>
      </MyModal>
    </>
  )
};

export default View;
